﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dapper_Core.AutoJob;
using Dapper_Core.BLL.Interface;
using Dapper_Core.Common;
using Dapper_Core.Table;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace Dapper_Core.Web.Areas.Sys.Controllers
{
    public class Sys_JobController : Controller
    {
        private readonly ISys_JobBusiness jobBusiness;
        public Sys_JobController(ISys_JobBusiness jobBusiness)
        {
            this.jobBusiness = jobBusiness;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult GetPageList(int rowsPerPage, int offsetRows, string search, string sortName, string sortOrder)
        {
            try
            {
                if (rowsPerPage < 1 || offsetRows < 0)
                {
                    return Json(new { total = 0, rows = new List<Sys_Job>() });
                }
                (List<Sys_Job> jobs, int count) = jobBusiness.GetPageList(offsetRows / rowsPerPage, rowsPerPage, search, sortName + " " + sortOrder);
                return Json(new { total = count, rows = jobs });
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "获取定时任务分页信息失败", $"rowsPerPage={rowsPerPage}，offsetRows={offsetRows}，search={search}，sortName={sortName}，sortOrder={sortOrder}", ex, "DapperCore");
                return Json(new { total = 0, rows = new List<Sys_Job>() });
            }
        }

        [HttpPost]
        public IActionResult Add(Sys_Job job)
        {
            try
            {
                #region 完善Sys_Job
                job.JobId = Guid.NewGuid().ToString();
                job.Creator = SessionUtility.GetBasicUserInfo().UserName;
                job.CreateDate = DateTime.Now;
                #endregion
                bool success = jobBusiness.Add(job);
                if (success)
                {
                    QuartzArtifiService.StartJob(job);
                    return Json(new { Success = true, Message = "添加成功！" });
                }
                return Json(new { Success = false, Message = "添加失败，请联系管理员！" });
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "系统定时任务添加失败", "job=" + JsonConvert.SerializeObject(job), ex, "DapperCore");
                return Json(new { Success = false, Message = "添加失败，请联系管理员！" });
            }
        }

        [HttpPost]
        public IActionResult Edit(Sys_Job job)
        {
            try
            {
                #region 完善Sys_Job
                Sys_Job old = jobBusiness.Get(job.JobId);
                old.JobName = job.JobName;
                old.JobType = job.JobType;
                old.JobCall = job.JobCall;
                old.JobCallParams = job.JobCallParams;
                old.Cron = job.Cron;
                old.Status = job.Status;
                old.Remarks = job.Remarks;
                old.Modifier = SessionUtility.GetBasicUserInfo().UserName;
                old.ModifyDate = DateTime.Now;
                #endregion
                bool success = jobBusiness.UpdateNotNull(old);
                if (success)
                {
                    QuartzArtifiService.HandleJob(job);
                    return Json(new { Success = true, Message = "修改成功！" });
                }
                return Json(new { Success = false, Message = "修改失败，请联系管理员！" });
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "系统定时任务修改失败", "job=" + JsonConvert.SerializeObject(job), ex, "DapperCore");
                return Json(new { Success = false, Message = "修改失败，请联系管理员！" });
            }
        }

        [HttpPost]
        public IActionResult Delete(string ids)
        {
            try
            {
                bool success = jobBusiness.Delete(ids, SessionUtility.GetBasicUserInfo().UserName);
                if (success)
                {
                    QuartzArtifiService.StopJob(ids);
                    return Json(new { Success = true, Message = "删除成功！" });
                }
                return Json(new { Success = false, Message = "删除失败，请联系管理员！" });
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "系统用户删除失败", "ids=" + ids, ex, "DapperCore");
                return Json(new { Success = false, Message = "删除失败，请联系管理员！" });
            }
        }
    }
}
